import React, { useEffect, useReducer, useState } from 'react'

/*
    hooks 只能在两个地方使用
        1、在函数式组件的最外层 
        2、在自定义hooks中我们可以 hooks 嵌套使用

    react 副作用:
        数据的订阅，事件订阅，数据请求，定时器等都为副作用
*/ 

// 1. 创建组件的初始状态
const initState = {
    bannerList: [],
    proList: []
}

// 2. 创建修改 state 的事件 reducer
const reducer = (state, action)=>{
    switch (action.type) {
        case 'change-banner-list':
            // 修改时数据
            return {...state, bannerList: action.payload}
        case 'change-pro-list':
            // 修改时数据
            return {...state, proList: action.payload}
        default:
            return state
    }
}
const App = () => {

    // 3. 通过初试状态和修改事件得到 state 和 dispatch 
    const [state,dispatch] = useReducer(reducer,initState)

    useEffect(()=>{
        fetch('http://121.89.205.189:3000/api/banner/list')
        .then(res => res.json())
        .then(res => {
            dispatch({
                type: 'change-banner-list',
                payload: res.data
            })
        })
    }, [])

    useEffect(()=>{
        fetch('http://121.89.205.189:3000/api/pro/list')
        .then(res => res.json())
        .then(res => {
            dispatch({
                type: 'change-pro-list',
                payload: res.data
            })
        })
    }, [])

    const pro = state.proList.map(item => (<li key={item.proid}>{item.proname}</li>))

  return (
    <div >
        <div>
            {
               state.bannerList.length > 0 &&
               state.bannerList.map(item => (<img key={item.bannerid} src={item.img} style={{width: 100}} />)) 
            }
        </div>

        <ol>
            {pro}
        </ol>
    </div>
  )
}

export default App